/*
    服务器
    多进程
*/

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <netinet/in.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <arpa/inet.h>
#include <pthread.h>
#include <time.h>

void* handle_client(void* avg)
{
    sleep(1);
    int new_fd = *((int*)avg);
    srand((unsigned long)time(NULL));

    char name[128];
    // ctime转化为
    sprintf(name, "%d_%ld.txt", rand(), pthread_self());
    // 接收文件
    char buffer[1024];
    memset(buffer, 0, sizeof(buffer));
    FILE *fp = fopen(name, "w");
    if (!fp)
    {
        perror("文件写入失败");
        exit(1);
    }
    int size = 0;
    while((size = read(new_fd, buffer, sizeof(buffer))) > 0)
    {
        fwrite(buffer, 1, size, fp);
        // 写入文件
        fflush(fp);
    }
    fclose(fp);
    printf("文件接收完毕,文件名：%s\n", name);
    // 回复用户
    // write(new_fd, "ok", 2);
    
    //不能写new_fd 地址不是一个地址
    free(avg);
    close(new_fd);
}

int main()
{
    // 1. 创建套接字
    // 参数 域  协议类型 协议0为默认
    int sever_fd = socket(AF_INET, SOCK_STREAM, 0);
    if(sever_fd == -1)
    {
        perror("套接字创建失败！");
        exit(1);
    }
    // 2.绑定ip和端口
    
    struct sockaddr_in sever_addr;
    // 清零 初始化
    memset(&sever_addr, 0, sizeof(sever_addr));
    sever_addr.sin_family = AF_INET;
    sever_addr.sin_port = htons(8888);      //把本地的小端序列，转化为网络字节序
    // sever_addr.sin_addr.s_addr = htonl(INADDR_ANY);     //接受任意ip的请求
    
    // 用于将 IPv4 或 IPv6 地址的字符串表示形式转换为二进制形式
    inet_pton(AF_INET, "0.0.0.0", &sever_addr.sin_addr.s_addr);
    int ret = bind(sever_fd, (struct sockaddr*)&sever_addr, sizeof(sever_addr));
    if(ret == -1)
    {
        perror("端口绑定失败！");
        exit(1);
    }
    // 3.监听端口
    ret = listen(sever_fd, 1024);
    if(ret == -1)
    {
        perror("listen");
        exit(1);
    }
    // 4.接收请求
    while(1)
    {
        // 客户端的
        struct sockaddr_in addr;
        memset(&addr, 0, sizeof(addr));
        addr.sin_family = AF_INET;
        int size = sizeof(addr);
        // 对应客户端套接字的文件描述符
        int new_fd = accept(sever_fd, (struct sockaddr*)&addr, &size);
        if(new_fd == -1)
        {
            perror("accept");
            exit(1);
        }
        if(fork() == 0)
        {
            // 子进程中
            int *pclient = (int*)malloc(sizeof(int));
            *pclient = new_fd;
            // 用户信息处理
            char text[INET_ADDRSTRLEN];
            // 把ip地址从网络字符序转化为字符串
            inet_ntop(AF_INET, &addr.sin_addr.s_addr, text, INET_ADDRSTRLEN);
            printf("客户端：ip地址 ：%s, 端口：%d\n", text, ntohs(addr.sin_port));
            pid_t pid = getpid();
            printf("进程 %d \n", pid);
            
            // 1. 读取文件名长度
            int name_len = 0;
            int n = read(new_fd, &name_len, sizeof(name_len));
            if (n != sizeof(name_len)) {
                perror("读取文件名长度失败");
                close(new_fd);
                exit(1);
            }
            // 2. 读取文件名
            char name[256] = {0};
            n = read(new_fd, name, name_len);
            if (n != name_len) {
                perror("读取文件名失败");
                close(new_fd);
                exit(1);
            }
            printf("接收到文件名: %s\n", name);

            char buf[1024];
            size_t size = 0;
            FILE *f = fopen(name, "w");
            while (0 != (size = read(new_fd, buf, 1024)))
            {
                printf("进程 %d 读取：%ld\n", pid, size);
                fwrite(buf, 1, size, f);
                memset(buf, 0, sizeof(buf));
            }
            fclose(f);
            printf("ok\n");
            exit(EXIT_SUCCESS);
        }
        else{
            close(new_fd);
        }
    }
    // 6.关闭连接
    close(sever_fd);
    return 0;
}